

package com.yeyks.aop;


import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.annotation.Login;
import com.yeyks.common.base.Arguments;
import com.yeyks.common.exception.PermissionInvalidException;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.commonReference.service.account.AccountInfoService;
import com.yeyks.web.AccountUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author administrator
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AccountInfoService accountService;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }
        //有NoLogin注解的不需要验证token，否则都要验证token
        if (annotation == null) {
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        if (Arguments.strIsNull(token)) {
            token = request.getHeader("headerToken");
        }
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }

        //token为空
        if (StringUtils.isBlank(token)) {
            throw new ServiceException("token不能为空");
        }


        AccountInfo operatorInfo = accountService.token2AccountInfo(token);
        if (null == operatorInfo) {
            throw new PermissionInvalidException();
        }
        if (!operatorInfo.getValid()) {
            throw new ServiceException("账号被禁用");
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, operatorInfo.getId());
        AccountUtils.putLoginUser(operatorInfo);
        return true;
    }
}
